package com.aop.aspectLog;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Date;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;


/**
 * 关注点：重复代码
 * 
 * 
 * 用动态代理  织入
 * 
 * 
 * 
 * @author My
 *
 */

@Component
@Aspect
public class TransactionAspect {
	
	//实现打印日记
	private static Logger logger= Logger.getLogger(TransactionAspect.class); 
	
	@Pointcut("execution(* com.aop.aspectLog.*.*(..))")
	public void printTitle(){}
	
	@Before(value="printTitle()")
	public void Tranq(){
		System.out.println("手写的切面开启事务");
	}
	
	@After(value="printTitle()")
	public void commit(){
		System.out.println("手写的切面提交事务");
		
	}
	
	@Around(value="printTitle()")
	public void round(ProceedingJoinPoint pjp) throws Throwable{
		
		
		
		//拿到sql
		Object proceed = pjp.proceed();
		String sql=(String)proceed;
		
		//参数  数组
		Object[] args = pjp.getArgs();
		
		Class.forName("com.mysql.jdbc.Driver");
		Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/spring", "root", "root");
		con.setAutoCommit(false);
		PreparedStatement ps = con.prepareStatement(sql);
		
		ps.setString(1, (String)args[0]);
		ps.setInt(2, (int)args[1]);
		
		try{
			
			int resutlNum = ps.executeUpdate();
			logger.info("插入成功"+sql+pjp.getArgs()[0]+pjp.getArgs()[1]+new Date());
			int a=10/0;
		}catch (Exception e){
			logger.info("插入失败"+sql+pjp.getArgs()[0]+pjp.getArgs()[1]+e+new Date());
		}
		
		con.commit();
		
	}

}
